import React, { useState, useEffect } from 'react';

export const App = () => {
  // 控制子组件消失和显示
  const [visible, setVisible] = useState(true);
  return (
    <div>
      <h2>父组件</h2>
      <button onClick={() => setVisible(!visible)}>消失/回来</button>
      <hr />
      {visible ? <Counter visible={visible} /> : null}
    </div>
  );
};

const Counter = () => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    // 组件加载完毕，effect 执行
    console.log('effect 执行');
    return () => {
      // 组件卸载时，或者引入新的 effect 时，执行清理函数
      console.log('effect清理函数执行');
    };
  }, [count]);

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={() => setCount(count + 1)}>+1</button>
    </div>
  );
};

export default App;
